import React, { useEffect, useRef, useState } from 'react'
import { X, RotateCcw, MessageCircle, Sparkles, Send, Plus } from 'lucide-react'
import { useChat } from '@/hooks/useChat'
import { Message } from './Message'
import { ChatInput } from './ChatInput'
import Vad from '@/components/Vad'

interface ChatWindowProps {
  isOpen: boolean
  onClose: () => void
}

export const ChatWindow: React.FC<ChatWindowProps> = ({ isOpen, onClose }) => {
  const { messages, isLoading, error, sendMessage, clearMessages } = useChat()
  const messagesEndRef = useRef<HTMLDivElement>(null)
  const [isRecording, setIsRecording] = useState(false)

  // 处理语音转文字后的消息
  const handleVoiceMessage = (message: string) => {
    if (message.trim()) {
      sendMessage(message)
    }
  }

  // 预设问题
  const suggestedQuestions = [
    "有什么好茶推荐",
    "什么是仙山八骏有机茶", 
    "详细介绍仙山八骏有机茶"
  ]

  // 自动滚动到最新消息
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
  }, [messages])

  if (!isOpen) return null
  return (
    <div className="fixed bottom-4 right-4 w-[400px] h-[680px] bg-white shadow-2xl border border-gray-100 flex flex-col z-50 overflow-hidden">
      {/* 头部 */}
      <div className="flex items-center justify-between px-6 py-4 bg-gradient-to-r from-blue-50 to-indigo-50 border-b border-gray-100">        <div className="flex items-center gap-3">
          <div className="w-8 h-8 bg-[#F6B610] flex items-center justify-center rounded-lg">
            <Sparkles className="w-5 h-5 text-white" />
          </div>
          <div>
            <h3 className="font-semibold text-gray-900">仙山八骏咨询</h3>
            <p className="text-xs text-gray-500">智能问答助手</p>
          </div>
        </div>
        <div className="flex items-center gap-1">          <button
            onClick={clearMessages}
            className="p-2 hover:bg-gray-100 transition-colors cursor-pointer"
            title="清空对话"
          >
            <RotateCcw className="w-4 h-4 text-gray-600" />
          </button>
          <button
            onClick={onClose}
            className="p-2 hover:bg-gray-100 transition-colors cursor-pointer"
            title="关闭"
          >
            <X className="w-4 h-4 text-gray-600" />
          </button>
        </div>
      </div>      
      {/* 消息区域 */}
      <div className="flex-1 overflow-y-auto">
        {messages.length === 0 ? (
          // 欢迎界面
          <div className="flex flex-col items-center justify-center h-full px-6 py-8">
            <div className="text-center mb-8">
              <h2 className="text-xl font-semibold text-gray-900 mb-2">
                你好，我是
              </h2>
              <h2 className="text-xl font-semibold text-[#F6B610] mb-4">
                仙山八骏智能助理
              </h2>
              <p className="text-sm text-gray-500 leading-relaxed">
                我可以帮助您解答问题、提供建议和进行智能对话
              </p>
            </div>    

            {/* 建议问题 */}
            <div className="w-full space-y-3">
              {suggestedQuestions.map((question, index) => (                <button
                  key={index}
                  onClick={() => sendMessage(question)}
                  className="w-full p-2 text-left bg-gray-50 hover:bg-gray-100 transition-colors group border border-gray-100"
                >
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-gray-700 flex-1">{question}</span>                    
                    <div className="opacity-0 group-hover:opacity-100 transition-opacity">
                      <div className="w-6 h-6 bg-gray-200 flex items-center justify-center">
                        <Plus className="w-3 h-3 text-gray-600 rotate-45" />
                      </div>
                    </div>
                  </div>
                </button>
              ))}
            </div>
          </div>
        ) : (
          // 对话消息
          <div className="px-4 py-4 space-y-4">
            {messages.map((message) => (
              <Message key={message.id} message={message} />
            ))}
            
            {isLoading && (
              <div className="flex justify-start">
                <div className="bg-gray-50 rounded-2xl px-4 py-3 max-w-[80%]">
                  <div className="flex items-center gap-2">
                    <span className="text-sm text-gray-600">思考中</span>
                    <div className="flex items-center gap-1">
                      <div className="w-2 h-2 bg-[#F6B610] rounded-full animate-bounce"></div>
                      <div className="w-2 h-2 bg-[#F6B610] rounded-full animate-bounce" style={{ animationDelay: '0.1s' }}></div>
                      <div className="w-2 h-2 bg-[#F6B610] rounded-full animate-bounce" style={{ animationDelay: '0.2s' }}></div>
                    </div>
                  </div>
                </div>
              </div>
            )}
            
            {error && (
              <div className="bg-red-50 border border-red-200 rounded-xl p-4">
                <p className="text-sm font-medium text-red-800">出错了</p>
                <p className="text-sm text-red-600 mt-1">{error}</p>
              </div>
            )}
            
            <div ref={messagesEndRef} />
          </div>
        )}
      </div>     
      {/* 输入区域 */}
      <div className="border-t border-gray-100 bg-white">
        <ChatInput 
          onSend={sendMessage} 
          disabled={isLoading}
          isRecording={isRecording}
          onRecordingChange={setIsRecording}
        />
        
        {/* Vad组件 */}
        {/* <Vad
          onMessage={handleVoiceMessage}
          recording={isRecording}
        /> */}
        
      </div>
    </div>
  )
}
